<template>
    <div class="order-detail">
        <UxDialog :visible="value" @show="onShow()" @close="onClose()">

            <div class="order-detail-warp">

                <!-- 请求出错 -->
                <div class="detail-error" v-if="error">
                    <p v-text="error"></p>
                    <button @click="getOrderDetail()">reload</button>
                </div>

                <!-- 未支付订单 -->
                <div class="detail-unpaid" v-else-if="info && [1, 13, 14].indexOf(info.order_state) > -1">

                    <OrderInfo :info="info" @update="update()" />

                    <div class="layout-content">
                        <OrderUnpaidAddress :info="info" @update="getOrderStatus()" :logistics.sync="logistics" :getLogistics="getLogistics" />
                        <OrderUnpaidSidebar :priceDetail="priceDetail" :forbid="false" :info="info" @payfor="paymentOpen()" />
                    </div>

                    <OrderUnpaidProduct :info="info" @update="getOrderStatus()" />

                    <!-- 自定义设计 -->
                    <OrderUnpaidCustomize />
                </div>

                <!-- 其他类型订单 -->
                <div class="detail-paid" v-else-if="info">

                    <!-- 订单信息 -->
                    <OrderInfo :info="info" @update="update()" />

                    <!-- 订单进度 -->
                    <OrderSteps :info="info" v-if="[11,12].indexOf(info.order_state) < 0" />

                    <div class="layout-content">
                        <div class="layout-process">
                            <!-- 订单状态 -->
                            <OrderPaidProcess :info="info" />
                            <!-- 购买的产品 -->
                            <OrderProductList :design="info.design" :info="info" @update="getOrderStatus()" />
                        </div>
                        <OrderPaidSidebar :info="info" :priceDetail="priceDetail" :logistics="logistics" />
                    </div>
                </div>

                <!-- 正在加载中 -->
                <UxLoading2 class="detail-loading" :loading="loading" />

            </div>
        </UxDialog>

        <!-- 支付对话框 -->
        <OrderPayment ref="payment" @paySuccess="paySuccess($event)" v-if="value" />

    </div>
</template>
<script>
import { mapGetters, mapState } from "vuex";
export default {
    name: "OrderDetail",
    props: {
        value: { type: Object, default: null },
    },
    data () {
        return {
            order_code: "", // 订单id
            loading: true,
            error: '',
            info: null,
            polling: 0,
            logistics: [], // 物流渠道
        };
    },
    computed: {

        ...mapState({
            currency: 'currency',
            rate: 'rate',
        }),

        priceDetail () {

            const pricing = (this.info || {}).pricing || {};
            const design = (this.info || {}).design || [];
            const mathRound = (value, n) => {
                n = n === undefined ? 1 : n;
                let bei = Math.pow(10, n);
                let res = Math.round(value * bei) / bei;
                return +parseFloat(res.toPrecision(12));
            }
            // 等级折扣
            const userDiscount = parseFloat(pricing.user_discount) || 100; // 折扣
            // 优惠劵折扣
            const couponDiscount = parseFloat(pricing.discount) || 100; // 折扣
            // 商品原价
            const result = {
                commodity: 0, // 商品单价（包括包装吊牌等）
                product: 0, // 商品原总价
                count: 0, // 商品数量
                tax: 0, // 税费
                shipping: 0, // 物流费
                total: 0, // 总价
                userLevel: 0, // 用户等级
                userDiscount: 0, // 用户等级折扣
                userDiscountLabel: 0, // 用户等级显示
                userDiscountPrice: 0, // 用户等级优惠的价格
                coupon: 0, // 优惠折扣比例百分比
                couponDiscount: 0, // 优惠折扣
                couponDiscountLabel: 0, // 优惠折扣显示
                couponDiscountPrice: 0,
                tag_price: 0, // 吊牌价格
                pack_price: 0, // 包装袋价格
                blank_price: 0, // 空白模板的优惠价格
            }


            design.map((item) => {

                // 数量
                const quantity = parseInt(item.count) || 0;
                const price = parseInt(item.price) || 0; // 订单详情中，price包含商品价格和设计面加价
                const tag_price = parseInt(item.tag_price) || 0;
                const pack_price = parseInt(item.pack_price) || 0;

                // 01.空白模板折扣后的价格
                // 空白模板差价  计算 5%折扣
                // ！！！！要取整
                // 当数量超过1时，要先算空白模板折扣再累加
                const product_blank = Math.ceil(price * (item.is_blank ? 0.95 : 1));

                // 02.用户等级折扣后的价格
                const product_level = 0.01 * product_blank * userDiscount;

                // 03.优惠折扣后的价格
                const product_coupon = 0.01 * product_level * couponDiscount;

                result.product += price * quantity;
                result.tag_price += tag_price * quantity;
                result.pack_price += pack_price * quantity;
                result.count += quantity;

                // 空白模板折扣价
                result.blank_price += (price - product_blank) * quantity;
                // 用户等级折扣价
                result.userDiscountPrice += (product_blank - product_level) * quantity;
                // 优惠劵折扣价
                result.couponDiscountPrice += (product_level - product_coupon) * quantity;

                // 商品价格
                // result.commodity += (product_coupon + pack_price + tag_price) * quantity;

            });

            result.product = Math.ceil(mathRound(result.product, 2));
            result.blank_price = Math.floor(mathRound(result.blank_price, 2));
            result.userDiscountPrice = Math.floor(mathRound(result.userDiscountPrice, 2));
            result.couponDiscountPrice = Math.floor(mathRound(result.couponDiscountPrice, 2));

            // 这个值没用到，是在orderUnpaidAddress直接用pricing.commodity_prices来计算
            result.commodity = parseInt(pricing.commodity_prices) || 0;
            // 这几个值不要变
            result.tax = parseInt(pricing.tax_price) || 0;
            result.shipping = parseInt(pricing.logistics_price) || 0;
            result.total = parseInt(pricing.total_money) || 0;

            result.userLevel = parseInt(pricing.userLevel) || 0;
            result.userDiscount = userDiscount;
            result.userDiscountLabel = parseInt(100 - userDiscount) + "% off";

            result.coupon = couponDiscount;
            result.couponDiscount = couponDiscount;
            result.couponDiscountLabel = parseInt(100 - couponDiscount) + "% off";

            return result
        },
    },
    methods: {
        // 对话框打开
        onShow () {
            // this.order_state = this.value.order_state;

            this.order_code = this.value.order_code;
            this.error = ''
            this.loading = true;
            this.getOrderDetail().then(info => {

                this.getLogistics(info).then(logistics => {
                    const state = info.state || {}
                    // pending中订单，轮询
                    if (state.order_state == 2 && state.order_pay_state == 1) {
                        setTimeout(this.getOrderStatus, 1000);
                    }

                    this.info = info;
                    this.logistics = logistics
                    this.loading = false;


                    // ----------------------------------
                    // 测试
                    // this.info.state.order_pay_state = 2;

                }).catch(err => {
                    this.info = info;
                    this.logistics = []
                    this.loading = false;

                })

            }).catch(err => {
                this.error = err
                this.loading = false;
            })
        },

        // 对话框关闭
        onClose () {
            this.info = null;
            this.polling && clearTimeout(this.polling);
            this.value && this.$emit("input", null);
        },


        // 从订单详情里获取数据
        async getOrderDetail () {

            let result = await this.$http("Order.getOrderDetail/" + this.order_code, { currency: this.currency });

            if (!this.value) {
                // 弹窗已经关了
            } else if (result.code === 0) {

                let data = result.data || {};
                let design = data.order_item || [];
                let logistics = data.logistics || {};
                let pricing = data.price_info || {};
                let state = data.state_info || {};


                // 商品格式化
                design.map((item) => {
                    item.design_list = JSON.parse(item.design_info || "[]");
                    item.model_img = JSON.parse(item.model_img || "[]");
                    item.quantity = item.count || 1;
                    item.extra_price = parseFloat(item.extra_price) || 0;
                    item.price = Math.round(item.price / item.quantity);
                    item.tag_price = Math.round(item.tag_price / item.quantity);
                    item.pack_price = Math.round(item.pack_price / item.quantity);
                    item.user_level = data.level;
                    item.user_discount = pricing.user_discount;


                    // 包装袋的信息了设计信息要处理一下
                    if (item.tag_design_info) {
                        item.tag_design_info.design = item.tag_design || '[]'
                        item.tag_design_info.total_price = item.tag_price;
                    }
                    if (item.pack_design_info) {
                        item.pack_design_info.design = item.pack_design || '[]'
                        item.pack_design_info.total_price = item.pack_price;
                    }

                    item.currency = data.currency
                    item.rate = data.rate
                });


                // 状态变更记录
                state.log_state = JSON.parse(state.log_state || '[]')

                // 测试
                // pricing.total_money = 300000
                // state.order_state = 9;
                // state.order_pay_state = 2;

                // 默认paypel支付
                pricing.payment = pricing.payment || 1;
                pricing.user_level = parseInt(data.level);

                return {
                    created_at: data.created_at, // 订单创建时间
                    third_order_code: data.third_order_code, // 第三方订单编号
                    order_type: data.order_type, // 订单类型
                    // shop_name: data.shop_name_text, // 第三方平台名称
                    all_custom_count: data.all_custom_count || 0, // 半自定义数量
                    order_code: data.order_code, // 订单编号
                    order_state: state.order_state, // 订单状态
                    currency: data.currency,
                    rate: data.rate,
                    updated_at: data.updated_at,

                    shop: {
                        shop_name: data.shop_name || '',
                        shop_name_text: data.shop_name_text || '',
                        shop_type: data.shop_type || '',
                    },

                    state: state, // 订单状态变更记录
                    address: data.customer || {}, // 收货地址
                    logistics: logistics, // 物流信息
                    design: design, // 下单商品
                    pricing: pricing, // 价格信息
                };


            } else {
                return Promise.reject(result.msg || "Failed to load order detail")
            }
        },

        // 获取物流列表
        async getLogistics (info, country_code, post_code) {
            const logistics = (info || {}).logistics || {};
            const address = (info || {}).address || {};
            const pricing = (info || {}).pricing || {};
            const request = {
                commodity_prices: pricing.commodity_prices + pricing.pack_price + pricing.tag_price,
                iso_code: country_code || address.country_code,
                weight: logistics.weight || 0,
                post_code: post_code || address.post_code || '',
            };

            if (request.iso_code) {
                const response = await this.$http("Order.getLogisticsInfo", request);
                const data = response.data || {}
                const list = [];
                Object.keys(data).map((key) => {
                    const item = data[key];
                    const no = {
                        pk_shipping: "PK",
                        tk_shipping: "TK",
                        ky_shipping: "KY",
                    };
                    const name = {
                        pk_shipping: "Standard",
                        ky_shipping: "Fast",
                        tk_shipping: "Express",
                    };

                    if (item.is_open) {
                        item.tax_price = data.tax_price;
                        item.remote_sign = data.remote_sign;
                        item.name = name[key];
                        item.no = no[key];
                        list.push(item);
                    }
                });

                if (response.code == 0 && list.length > 0) {
                    return list;
                } else {
                    return Promise.reject(result.msg || "Failed to load shipping")
                }
            } else {
                return Promise.reject("No logistics information")
            }
        },


        // 更新订单状态
        async getOrderStatus () {

            let code = (this.info || {}).order_code;
            let state = (this.info || {}).state || {};
            let response = await this.$http("Order.getOrderStatus", { order_codes: [code] });
            let status = (response.data || []).filter(i => i.order_code == code)[0] || {};

            // 轮询
            let doLoop = () => {
                if (!this.info) {
                    // 没有状态
                } else if (this.info.state.order_state != 2) {
                    // 不是已支付状态
                } else if (this.info.state.order_pay_state != 1) {
                    // 不是panding
                } else {
                    this.polling && clearTimeout(this.polling);
                    this.polling = setTimeout(this.getOrderStatus, 1000);
                }
            }

            if (response.code === 0) {
                // 成功了
                if (!status) {
                    // 没找到
                } else if (status.order_state == state.order_state && status.order_pay_state == state.order_pay_state) {
                    // 没有变更
                } else {
                    const stateChange = state.order_state != status.order_state;

                    this.info.order_state = status.order_state;
                    this.info.state.order_state = status.order_state;
                    this.info.state.order_pay_state = status.order_pay_state;

                    stateChange && this.$emit("reload");
                }
                doLoop();
            } else {
                this.$uxMessage.error(response.msg, "Get order status Failed");
                doLoop();
            }
        },

        // 更新
        update () {

            this.loading = true;
            this.getOrderDetail().then(info => {
                this.info = info
                this.loading = false;
                this.$emit("reload");
                if (this.info.state.order_state == 2 && this.info.state.order_pay_state == 1) {
                    setTimeout(this.getOrderStatus, 1000);
                }
            }).catch(err => {
                this.loading = false;
            })
        },

        // 打开
        paymentOpen () {

            const design = (this.info || {}).design || [];
            const option = {
                amount: this.priceDetail.total,
                codes: this.order_code,
                product: [],
                shipping: this.info.address,
                action: 'single',
            }

            option.product = design.map(item => {
                return {
                    name: item.title,
                    sku: item.sku,
                    price: parseInt(item.price + item.extra_price),
                    count: parseInt(item.count)
                }
            })

            this.$refs.payment.open(option);
        },

        // 支付成功
        paySuccess (status) {
            this.update();
        },

    },
    created () {
        this.$on('global:ORDER_DETAIL_CLOSE', this.onClose);
    },
    beforeDestroy () {
        this.polling && clearTimeout(this.polling);
    },
};
</script>
<style lang="scss" scoped>
.order-detail-warp {
    box-sizing: border-box;
    min-height: calc(100vh - 80px);
    width: calc(100vw - 80px);
    min-width: 900px;
    max-width: 1100px;
    display: flex;
    flex-direction: column;
    background: #f8f8f8;
    border-radius: 12px;
    position: relative;
    padding: 22px 18px 18px;

    .detail-loading {
        border-radius: 12px;
    }

    .detail-error {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        p {
            line-height: 40px;
            font-size: 16px;
        }

        button {
            margin-top: 8px;
            height: 32px;
            width: 80px;
        }
    }
}

.detail-unpaid {
    .layout-content {
        display: flex;
        margin-top: 32px;
    }
    .order-address {
        flex: 1;
        margin-right: 12px;
    }
    .order-sidebar {
        width: 252px;
        box-sizing: border-box;
    }
}

.detail-paid {
    .layout-content {
        display: flex;
        position: relative;
        margin-top: 32px;
    }

    .layout-process {
        flex: 1;
        margin-right: 12px;
    }
    .order-sidebar {
        width: 252px;
    }
}
</style>
